package com.mashibing.juc.c_020;

import java.util.concurrent.Semaphore;
import java.util.concurrent.TimeUnit;

public class T11_TestSemaphore {

    public static void main(String[] args) throws Exception {
        //Semaphore s = new Semaphore(2);
        Semaphore semaphore = new Semaphore(2, true);
        //允许一个线程同时执行
        //Semaphore s = new Semaphore(1);

//        System.out.println(semaphore.drainPermits());
        System.out.println(semaphore.availablePermits());

        new Thread(()->{
            try {
                semaphore.acquireUninterruptibly(2);
//                s.acquire();

                System.out.println("T1 running...1");
                Thread.sleep(2000);
                System.out.println("T1 running...2");

            } catch (InterruptedException e) {
                e.printStackTrace();
            } finally {
                semaphore.release();
            }
        }, "thread1").start();
        System.out.printf("\033[34m 是否有线程正在等待 ===>> %s ===>> %s \033[0m\n",
                semaphore.hasQueuedThreads(), semaphore.getQueueLength());

        Thread thread2 = new Thread(() -> {
            try {
//                s.acquireUninterruptibly();
                semaphore.acquire();

                System.out.println("T2 running...1");
//                Thread.sleep(2000);
                System.out.println("T2 running...2");

            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                semaphore.release();
            }
        }, "thread2");
        thread2.start();
        System.out.printf("\033[34m 是否有线程正在等待 ===>> %s ===>> %s \033[0m\n",
                semaphore.hasQueuedThreads(), semaphore.getQueueLength());

        Thread thread3 = new Thread(() -> {
            try {
                semaphore.acquireUninterruptibly();
//                s.acquire();

                System.out.println("T3 running...1");
//                Thread.sleep(2000);
                System.out.println("T3 running...2");

            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                semaphore.release();
            }
        }, "thread3");
        System.out.printf("\033[34m 是否有线程正在等待 ===>> %s ===>> %s \033[0m\n",
                semaphore.hasQueuedThreads(), semaphore.getQueueLength());
        thread3.start();

        TimeUnit.MILLISECONDS.sleep(1234);
        thread2.interrupt();
    }

}
